package com.ys.web.hjzf.controller;


import com.alibaba.fastjson.JSON;
import com.ys.utils.base.j2se.DateUtil;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.hjzf.HjzfHandler;
import com.ys.utils.hjzf.sdk.entity.Response;
import com.ys.utils.hjzf.sdk.utils.JsonUtil;
import com.ys.utils.hjzf.sdk.utils.RSAUtil;
import com.ys.utils.pay.Result;
import com.ys.web.hjzf.model.TransNotify;
import com.ys.web.hjzf.service.HjzfService;
import com.ys.web.mobao.service.MobaoWithholdingService;
import com.ys.web.pay.PayEnum;
import com.ys.web.pay.PayService;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.PayOrder;
import com.ys.web.pay.model.WithdrawRecord;
import com.ys.web.user.info.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/hjzf/callBack")
public class HjzfCallBackController {
    @Autowired
    private HjzfService hjzfService;
    @Autowired
    private PayService payService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MobaoWithholdingService mobaoWithholdingService;

    /**
     * 支付回调接口
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    public String payNotify(HttpServletRequest request,@RequestAttribute String json){
        try {
            Response response = null;
            Map<String,Object> map = Json.fromJson(Map.class,json);
            if(StringHandler.isNotEmpty(map.get("jsonParam"))){
                Map<String,Object> jsonParam = JsonUtil.toBean(map.get("jsonParam")+"",Map.class);
                response = JsonUtil.toBean(JsonUtil.toString(jsonParam),Response.class);
            }
            String signStr = HjzfHandler.getSortedString(response);
//            System.out.println("待签名字符串：" + signStr);// 待签名字符串
            //待签名字符串
            String data = signStr;
            //平台公钥验签
            String pubkey = HjzfHandler.publicKeyStr;
            //异步通知返回的sign
            String sign = response.getSign();
            /*
             * @param data      需要验签的数据（待签名字符串）
             * @param publicKey 平台公钥
             * @param sign      用户传过来的签名串（异步sign）
             */
            boolean a = RSAUtil.verify(data, pubkey, sign, false);
            if(a){
                Map<String,String> payData = JsonUtil.toBean(response.getData(),Map.class);
                if(StringHandler.isNotEmpty(payData.get("order_status"))){
                    if(payData.get("order_status").equals("P1000")) {
                        PayOrder payOrder = payService.payOrderByNo(payData.get("mch_order_no"));
                        if (payOrder.payStatus.equals("1")) {
                            return "success";
                        }
                        // 更新订单状态
                        PayOrder _payOrder = new PayOrder();
                        _payOrder.setId(payOrder.getId());
                        _payOrder.setPayStatus(PayEnum.PayStatus.PAID.getCode());
                        _payOrder.setPayTime(new Date());
                        _payOrder.setDayKey(DateUtil.getYYMMDD());
                        _payOrder.setSerialNumber(payData.get("jp_order_no"));
                        int i = payService.payOrderStatusChange(_payOrder);
                        if (i <= 0) {
                            return "success";
                        }
                        Result<?> result1 = PayManager.accountModifyHjzf(StringHandler.getLong(payOrder.getBusyId()), PayEnum.AccountFlowType.TYPE_RECHARGE,
                                payOrder.getAmount(),
                                String.format("余额充值-来自%s(%s)", payOrder.getBankName(), payOrder.getCardNo().substring(payOrder.getCardNo().length() - 4)));

//                    try {
//                        UserInfo userInfo = userInfoService.getUserInfoById(StringHandler.getLong(payOrder.getBusyId()));
//                        if(StringHandler.isNotEmpty(userInfo)) {
//                            //发送短信
//                            Map<String, Object> msgMap = new HashMap<>();
//                            msgMap.put("money", StringHandler.fenToYuan(payOrder.amount + ""));
//                            msgMap.put("name", StringHandler.isEmpty(userInfo.getPhone())?userInfo.getNickName():userInfo.getPhone());
//                            if(StringHandler.isNotEmpty( userInfo.getPhone())){
//                                SendSmsResponse sendSmsResponse = AliyunSmsUtils.sendMsg(Config.pp.get("ys.sms.recharge.id"), userInfo.getPhone(), JSON.toJSONString(msgMap));
//                                if (!sendSmsResponse.getCode().equals("OK")) {
//                                    log.error("充值短信提示发送失败：" + JSON.toJSON(sendSmsResponse));
//                                }
//                            }
//                        }
//                    } catch (ServerException e) {
//                        e.printStackTrace();
//                    } catch (ClientException e) {
//                        e.printStackTrace();
//                    } catch (Exception e) {
//                        log.error("充值短信提示发送错误",e);
//                    }
                        if (!result1.success()) {
                            Logger.error("汇聚支付充值--修改账户金额失败：" + JSON.toJSONString(map));
                            return "FAIL";
                        }
                    }else if(payData.get("order_status").equals("P3000")){
                        //订单在处理中
                        return "FAIL";
                    }else{
                        // 充值失败
                        PayOrder payOrder = payService.payOrderByNo(payData.get("mch_order_no"));
                        // 更新订单状态
                        PayOrder _payOrder = new PayOrder();
                        _payOrder.setId(payOrder.getId());
                        _payOrder.setPayStatus(PayEnum.PayStatus.FAIL.getCode());
                        payService.payOrderStatusChange(_payOrder);
                        return "success";
                    }
                }else{
                    Logger.error("汇聚支付充值回调----订单状态错误");
                    return "FAIL";
                }
                return "success";
            }
        }catch (Exception e){
            Logger.error(e);
        }
        return "FAIL";
    }

    /**
     * 转账回调接口
     * @param json
     * @return
     */
    @RequestMapping("/transNotify")
    public String transNotify(HttpServletRequest request,@RequestAttribute String json){
        try {
            if(StringHandler.isEmpty(json)){
                return "{\"statusCode\":\"2000\", \"message\":\"返回信息为空\"}";
            }
            TransNotify transNotify = null;
            Map<String,Object> map = Json.fromJson(Map.class,json);
            if(StringHandler.isNotEmpty(map.get("jsonParam"))){
                Map<String,Object> jsonParam = JsonUtil.toBean(map.get("jsonParam")+"",Map.class);
                transNotify = JsonUtil.toBean(JsonUtil.toString(jsonParam),TransNotify.class);
            }
            log.info("transNotify---------"+JsonUtil.toString(json));
            //待签名字符串
            String signStr = HjzfHandler.getTransResponseSign(transNotify);
            System.out.println("待签名字符串：" + signStr);// 待签名字符串
            //平台公钥验签
            //异步通知返回的sign
            String sign = transNotify.hmac;
            /*
             * @param data      需要验签的数据（待签名字符串）
             * @param publicKey 平台公钥
             * @param sign      用户传过来的签名串（异步sign）
             */
            WithdrawRecord withdrawRecord = mobaoWithholdingService.getWithdrawRecordByOrderId(transNotify.merchantOrderNo);
            if(transNotify.status==205){
                boolean a = RSAUtil.verify(signStr, HjzfHandler.publicTransKeyStr, sign, false);
                if(a){
                    if(StringHandler.isEmpty(withdrawRecord)){
                        log.info("汇聚支付回调----["+transNotify.merchantOrderNo+"]----提现信息不存在");
                        return "{\"statusCode\": \"2001\", \"message\": \"成功\"}";
                    }
                    if(StringHandler.getInt(withdrawRecord.withdrawStatus)==2){
                        log.info("汇聚支付回调----["+transNotify.merchantOrderNo+"]----提现已经成功");
                        return "{\"statusCode\": \"2001\", \"message\": \"成功\"}";
                    }
                    int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
                    if(i <= 0) {
                        Logger.info("汇聚支付回调处理中订单--该订单已处理", json);
                        return "{\"statusCode\": \"2001\", \"message\": \"成功\"}";
                    }
                    //提现成功扣除冻结金额
                    PayManager.accountModifyHjzf(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, withdrawRecord.getAmount(), withdrawRecord.getUserId()+":提现成功扣除冻结金额");
                    withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                    withdrawRecord.orderOutNo=transNotify.platformSerialNo;
                    //添加手续费账户累计资金
//                        try {
//                            UserInfo userInfo = userInfoService.getUserInfoById(StringHandler.getLong(withdrawRecord.getUserId()));
//                            if(StringHandler.isNotEmpty(userInfo)) {
//                                //发送短信
//                                Map<String, Object> msgMap = new HashMap<>();
//                                msgMap.put("money", StringHandler.fenToYuan(withdrawRecord.getWithdrawAmount() + ""));
//                                msgMap.put("name", StringHandler.isEmpty(userInfo.getPhone())?userInfo.getNickName():userInfo.getPhone());
//                                if(StringHandler.isNotEmpty( userInfo.getPhone())){
//                                    SendSmsResponse sendSmsResponse = AliyunSmsUtils.sendMsg(Config.pp.get("ys.sms.withdraw.id"), userInfo.getPhone(), JSON.toJSONString(msgMap));
//                                    if (!sendSmsResponse.getCode().equals("OK")) {
//                                        log.error("提现短信提示发送失败：" + JSON.toJSON(sendSmsResponse));
//                                    }
//                                }
//                            }
//                        } catch (ServerException e) {
//                            e.printStackTrace();
//                        } catch (ClientException e) {
//                            e.printStackTrace();
//                        } catch (Exception e) {
//                            log.error("提现短信提示发送错误",e);
//                        }
                }else{
                    int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
                    if(i <= 0) {
                        Logger.info("提现回调给到处理中订单--该订单已处理", json);
                        return "{\"statusCode\": \"2001\", \"message\": \"成功\"}";
                    }
                    //提现失败退回余额
//                    PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_FAIL, withdrawRecord.getAmount(), Convert.objToStr(withdrawRecord.getUserId()),2);
                    withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
                    withdrawRecord.remark = "汇聚提现签名错误";
                }
            }else if(transNotify.status==201 || transNotify.status==202 || transNotify.status==203 || transNotify.status==210 || transNotify.status==211 || transNotify.status==213) {
                Logger.info("汇聚提现回调给到处理中订单--返回状态处理中", json);
                return "{\"statusCode\": \"2000\", \"message\": \"返回状态处理中\"}";
            }else{
                int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
                if(i <= 0) {
                    Logger.info("汇聚支付回调处理中订单--该订单已处理", json);
                    return "{\"statusCode\": \"2001\", \"message\": \"成功\"}";
                }
                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
                withdrawRecord.remark = "汇聚提现返回失败:"+transNotify.errorCodeDesc;
            }
            withdrawRecord.setDayKey(DateUtil.getYYMMDD());
            mobaoWithholdingService.updateWithdrawRecordStatusTask(withdrawRecord);
            return "{\"statusCode\": \"2001\", \"message\": \"成功\"}";
        }catch (Exception e){
            Logger.error(e);
        }
        return "{\"statusCode\": \"2000\", \"message\": \"返回状态错误\"}";

    }
}
